package cn.zxh.csdn_maven.work.flow.login.chains;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import cn.zxh.csdn_maven.base.pojo.Cookies;
import cn.zxh.csdn_maven.work.flow.login.AbstractFlowController;
@SuppressWarnings(value={"unused"})
public class HiddenFlow extends AbstractFlowController {

	private Logger logger = Logger.getLogger(HiddenFlow.class);

	@Override
	public Map<String, Object> execute(HttpClient client,Map<String, Object> params) throws ClientProtocolException, IOException {

		Map<String, Object> result = new HashMap<String, Object>();
		// 访问登录页面，额外数据就在表单中隐藏
		HttpGet httpGet = new HttpGet(getBaseUrl());
		HttpResponse response = client.execute(httpGet);
		if(response.getStatusLine().toString().indexOf("200")!=-1){
			result.put("msg", "success");
		}
		/** 第一时间设置cookie */
		if(response.getHeaders("Set-Cookie")!=null){
			Cookies.setCookies(response.getHeaders("Set-Cookie"));
		}
		String html = EntityUtils.toString(response.getEntity());
		httpGet.releaseConnection();
		String regex = "hm.src.*;";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(html);
		String otherUrl = "";
		while (m.find()) {
			otherUrl = m.group();
			otherUrl = otherUrl.substring(otherUrl.indexOf("http"),otherUrl.lastIndexOf("\""));
			HttpGet httpGet_child = new HttpGet(otherUrl);
			/** 链接不用了。需要将client关闭 */
			httpGet_child.addHeader("Referer", getBaseUrl());
			HttpResponse response_child = client.execute(httpGet_child);
			httpGet_child.releaseConnection();
			/** 第一时间设置cookie */
			Cookies.setCookies(response_child.getHeaders("Set-Cookie"));
		}

		Document document = Jsoup.parse(html);
		Element form = document.getElementById("fm1");
		/** 获取额外参数 */
		Elements hiddens = form.select("input[type=hidden]");
		for (Element input : hiddens) {
			result.put(input.attr("name"), input.attr("value"));
		}
		result.put("action", form.attr("action"));
		return result;
	}

	@Override
	public String getBaseUrl() {
		return "https://passport.csdn.net/account/login";
	}

}
